#include "head.h"


int son(int local_fd)
{
    while(1)
    {
        // 得到与用户交互的 sock_fd
        int sock_fd = 0;
        local_recv(local_fd, &sock_fd);

        // 与客户端交互
        
        // 接收文件名信息
        int file_mame_len = 0;
        if(recv(sock_fd, &file_name_len, sizeof(int), MSG_WAITALL) == -1)
            error(1, errno, "recv");
        
        char file_name[50] = {0};
        if(recv(sock_fd, buf, file_name, MSG_WAITALL) == -1)
            error(1, errno, "recv");
        //打开文件
        int file_fd = open(file_name, O_RDWR);//////////// 
        fstat()
        if(send(sock_fd, , 5, 0) == -1)
            error(1, errno, "send");
        printf("1.count = %d\n", count);

        count = send(local_fd, "huzhu", 5, 0);
        printf("2.count = %d\n", count);
        
        // close(sock_fd);
    }
}


int allocating_task(Process pool[], int n, int sock_fd, int epoll_fd)
{
    for(int i = 0; i < n; ++i)
    {
        if(pool[i].state == FREE)
        {
            // 父进程把与用户端交互的权利交给子进程
            local_send(pool[i].local_fd, sock_fd);
            
            pool[i].state = BASY;

            // 父进程断开和用户端的连接
            epoll_pool_del(sock_fd, epoll_fd);
            close(sock_fd);

            // 父进程等待子进程完成任务的回复
            char buf[6] = {0};
            recv(pool[i].local_fd, buf, sizeof(buf) - 1, MSG_WAITALL);

            if(strcmp(buf, "huzhu") == 0)
                printf("子进程完成了任务\n");
            else
                printf("子进程疯了\n");

            pool[i].state = FREE;
        }
        if(i == n - 1)
            printf("系统繁忙\n");
    }

}


int add_usr(int fd, int current, int epoll_fd)
{
    int sock_fd = accept(fd, NULL, NULL);
    if(sock_fd == -1)
        error(1, errno, "accept");
    
    printf("新用户加入\n");
    epoll_pool_add(sock_fd, epoll_fd);

    return 0;
}